package com.dxysun.design.proxy.cglibproxy;

import java.lang.reflect.Method;

import com.dxysun.design.proxy.RealSubject;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class CGlibProxy implements MethodInterceptor
{

	public Object getInstance(Class<?> clazz) throws Exception
	{
		//相当于Proxy，代理的工具类
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(clazz);
		enhancer.setCallback(this);
		return enhancer.create();
	}

	public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable
	{
		before();
		Object obj = methodProxy.invokeSuper(o, objects);
		after();
		return obj;
	}

	private void before()
	{
		System.out.println("cglib call service before");
	}

	private void after()
	{
		System.out.println("cglib call service after");
	}

	public static void main(String[] args) throws Exception
	{
		CGlibProxy cGlibProxy = new CGlibProxy();
		RealSubject realSubject = (RealSubject) cGlibProxy.getInstance(RealSubject.class);
		realSubject.request();
	}
}
